package com.example.safeassistan.hiddendanger.fragment;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseVPFragment;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.hiddendanger.activity.HiddendangerUnSubmit;
import com.example.safeassistan.hiddendanger.adapter.HiddenDangerDepartmentAdapter;
import com.example.safeassistan.hiddendanger.adapter.HiddenDangerMyAdapter;
import com.example.safeassistan.hiddendanger.adapter.HiddenDangerStatusAdapter;
import com.example.safeassistan.hiddendanger.model.DepartModel;
import com.example.safeassistan.hiddendanger.model.HiddenDangerMyModel;
import com.example.safeassistan.hiddendanger.model.HiddenDangerTotalUser;
import com.example.safeassistan.hiddendanger.model.StatusModel;
import com.example.safeassistan.home.activity.OverDueHiddenDangerDetail;
import com.example.safeassistan.home.adapter.HiddenDangerDepartmentsAdapter;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.risk.model.DepartListModel;
import com.example.safeassistan.utile.JsonUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class HiddenDangerDepartmentFragment extends BaseVPFragment implements View.OnClickListener {
    private Context context;
    private View view;
    private SmartRefreshLayout refresh;
    private HiddenDangerDepartmentAdapter adapter;
    private HiddenDangerDepartmentsAdapter departmentsAdapter;
    private List<HiddenDangerMyModel.ResultDTO> data;
    private RecyclerView rcView;
    private LinearLayout llType1,llType2,llType3;
    private TextView tvType1,tvType2,tvType3;
    private String departId="";
    private int level=-1;//等级 1 重大 3 一般
    private int status=-1;// 1待提交 2待评审 3待整改4待验收5已完成6已撤销
    private List<StatusModel> ststusHandle;
    DepartModel departListModel;
    private HiddenDangerStatusAdapter statusAdapter;
    private TextView tvCommonHiddenDanger,tvBigHiddenDanger,tvTotal;


    public static HiddenDangerDepartmentFragment newInstance(int  type) {
        Bundle arguments = new Bundle();
        arguments.putInt("type",type);
        HiddenDangerDepartmentFragment fl = new HiddenDangerDepartmentFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.hiddendanger_department_fragment, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    public void initView(){
        refresh=view.findViewById(R.id.refresh);
        refresh.finishRefreshWithNoMoreData();
        ststusHandle=new ArrayList<>();
        ststusHandle.add(new StatusModel("待提交",1));
        ststusHandle.add(new StatusModel("待评审",2));
        ststusHandle.add(new StatusModel("待整改",3));
        ststusHandle.add(new StatusModel("待验收",4));
        ststusHandle.add(new StatusModel("已撤销",6));
        ststusHandle.add(new StatusModel("已通过",5));

        llType1=view.findViewById(R.id.llType1);
        llType2=view.findViewById(R.id.llType2);
        llType3=view.findViewById(R.id.llType3);
        rcView=view.findViewById(R.id.rcView);
        tvType1=view.findViewById(R.id.tvType1);
        tvType2=view.findViewById(R.id.tvType2);
        tvType3=view.findViewById(R.id.tvType3);
        tvCommonHiddenDanger=view.findViewById(R.id.tvCommonHiddenDanger);
        tvBigHiddenDanger=view.findViewById(R.id.tvBigHiddenDanger);
        tvTotal=view.findViewById(R.id.tvTotal);
        llType1.setOnClickListener(this::onClick);
        llType2.setOnClickListener(this::onClick);
        llType3.setOnClickListener(this::onClick);
        rcView=view.findViewById(R.id.rcView);

        data=new ArrayList<>();
        setView();
    }

    public void setView(){
        data=new ArrayList<>();
        refresh.finishRefreshWithNoMoreData();
        refresh.setEnableAutoLoadMore(false);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getData();
                    }
                }, 1000);
            }
        });
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible){
            getTopData();
            getData();
        }
    }

    @Override
    protected void onFragmentFirstVisible() {
        getDepartListData();
    }

    PopupWindow popupWindow=null;

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llType1:
                View inflate = LayoutInflater.from(context).inflate(R.layout.popu_hiddendanger_department,null);
                RecyclerView rcDepartment=inflate.findViewById(R.id.rcDepartment);
                TextView tvDepart=inflate.findViewById(R.id.tvDepart);

                tvDepart.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                        tvType1.setText("部门");
                        tvType1.setTextColor(context.getResources().getColor(R.color.gray3));
                        departId="";
                        getData();
                    }
                });
                rcDepartment.setLayoutManager(new LinearLayoutManager(context));
                departmentsAdapter=new HiddenDangerDepartmentsAdapter(departListModel.getResult());
                rcDepartment.setAdapter(departmentsAdapter);
                departmentsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        popupWindow.dismiss();
                        tvType1.setText(departListModel.getResult().get(position).getName());
                        tvType1.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        departId=departListModel.getResult().get(position).getId();
                        getData();
                    }
                });
                popupWindow = new PopupWindow(inflate, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llType1,0,-100);
                break;
            case R.id.llType2:
                View inflate1 = LayoutInflater.from(context).inflate(R.layout.popu_hiddendanger_level,null);
                TextView tvBig=inflate1.findViewById(R.id.tvUn);
                TextView tvCommon=inflate1.findViewById(R.id.tvAl);
                TextView tvAll=inflate1.findViewById(R.id.tvAll);
                tvBig.setWidth(llType2.getWidth());
                tvAll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        level=-1;
                        tvType2.setText("等级");
                        tvType2.setTextColor(context.getResources().getColor(R.color.gray3));
                        popupWindow.dismiss();
                        getData();
                    }
                });

                tvBig.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //重大隐患
                        level=3;
                        tvType2.setText("重大隐患");
                        tvType2.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        popupWindow.dismiss();
                        getData();
                    }
                });
                tvCommon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //一般隐患
                        level=1;
                        tvType2.setText("一般隐患");
                        tvType2.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        popupWindow.dismiss();
                        getData();
                    }
                });
                popupWindow = new PopupWindow(inflate1, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llType2,0,-100);
                break;
            case R.id.llType3:
                statusAdapter=new HiddenDangerStatusAdapter(ststusHandle);
                View inflate2 = LayoutInflater.from(context).inflate(R.layout.popu_hiddendanger_status,null);
                TextView tvTitle=inflate2.findViewById(R.id.tvTitle);
                RecyclerView rcCommon=inflate2.findViewById(R.id.rcCommon);
                rcCommon.setLayoutManager(new LinearLayoutManager(context));
                rcCommon.setAdapter(statusAdapter);

                tvTitle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        status=-1;
                        tvType3.setText("状态");
                        tvType3.setTextColor(context.getResources().getColor(R.color.gray3));
                        popupWindow.dismiss();
                        getData();
                    }
                });

                statusAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        status=statusAdapter.getData().get(position).getId();
                        tvType3.setText(statusAdapter.getData().get(position).getText());
                        tvType3.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        popupWindow.dismiss();
                        getData();
                    }
                });
                tvTitle.setWidth(llType3.getWidth());
                popupWindow = new PopupWindow(inflate2, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llType3,0,-100);
                break;
        }
    }

    public void getData(){
        JSONObject map = new JSONObject();
        try {
            if (level!=-1){
                map.put("level",level);//隐患等级
            }
            if (!departId.equals("")){
                map.put("departId",departId);//处理状态
            }
            if (status!=-1){
                map.put("disposeStatus",status);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.queryHiddenDangerByDepart, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        refresh.finishRefresh();
                        Object obj = JsonUtils.fromJson(result.toString(), HiddenDangerMyModel.class);
                        if (obj instanceof HiddenDangerMyModel) {
                            HiddenDangerMyModel model=(HiddenDangerMyModel) obj;
                            data.clear();
                            if (model.getResult().size() > 0) {
                                data=model.getResult();
                                adapter=new HiddenDangerDepartmentAdapter(data);
                                rcView.setLayoutManager(new LinearLayoutManager(context));
                                rcView.setAdapter(adapter);
                                adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                                        OverDueHiddenDangerDetail.actionStart(context,model.getResult().get(position).getDisposeStatus()+"",1,
                                                model.getResult().get(position).getId(),model.getResult().get(position).getRectSubmit());

                                    }
                                });
                                rcView.setNestedScrollingEnabled(false);
                            } else {
                                adapter.notifyDataSetChanged();
                            }
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                refresh.finishRefresh();
            }
        });
    }


    public void getDepartListData(){
        new HttpRequest(context).doPost(UrlConstants.getDepartById, null, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), DepartModel.class);
                        if (obj instanceof DepartModel) {
                             departListModel=(DepartModel) obj;
                        }else {
                            Log.e("aaaa","哈哈哈哈哈");
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    public void getTopData(){
        new HttpRequest(context).doPost(UrlConstants.getDefectTotalByDepart, null, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), HiddenDangerTotalUser.class);
                        if (obj instanceof HiddenDangerTotalUser) {
                            HiddenDangerTotalUser model=(HiddenDangerTotalUser) obj;
                            tvBigHiddenDanger.setText(model.getResult().get(1).getNum()+"");
                            tvCommonHiddenDanger.setText(model.getResult().get(0).getNum()+"");
                            tvTotal.setText(Integer.parseInt(model.getResult().get(0).getNum())+Integer.parseInt(model.getResult().get(1).getNum())+"");
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }
}